<template>
	<div class="page-container">
		<h1>AES/DES加密解密工具</h1>
		<el-form :model="form" label-position="top">
			<el-form-item label="明文/密文">
				<el-input v-model.trim="form.text" placeholder="请输入要加密或解密的文本"></el-input>
			</el-form-item>
			<el-form-item label="密码">
				<el-input v-model.trim="form.password" placeholder="请输入密码"></el-input>
			</el-form-item>
			<el-form-item label="密钥长度">
				<el-input-number v-model="form.keySize" :min="1" :max="1000"></el-input-number>
			</el-form-item>
			<el-form-item label="选择加密算法">
				<el-radio-group v-model="form.algorithm">
					<el-radio-button label="AES">AES</el-radio-button>
					<el-radio-button label="DES">DES</el-radio-button>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="操作类型">
				<el-radio-group v-model="form.operation">
					<el-radio-button label="encrypt">加密</el-radio-button>
					<el-radio-button label="decrypt">解密</el-radio-button>
				</el-radio-group>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="execute">执行</el-button>
			</el-form-item>
		</el-form>
		<el-form label-position="top">
			<el-form-item label="结果">
				<el-input v-model="resultText"></el-input>
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	import CryptoJS from "crypto-js";

	export default {
		data() {
			return {
				form: {
					text: "",
					password: "",
					keySize: 128,
					algorithm: "AES",
					operation: "encrypt",
				},
				resultText: "",
			};
		},
		methods: {
			execute() {
				const text = this.form.text;
				const password = this.form.password;
				const keySize = this.form.keySize;
				const algorithm = this.form.algorithm;
				const operation = this.form.operation;

				if (!text) {
					this.$message.error("请输入要加密或解密的文本！");
					return;
				}

				if (!password) {
					this.$message.error("密码不能为空！");
					return;
				}

				let result;
				if (algorithm === "AES") {
					if (operation === "encrypt") {
						result = CryptoJS.AES.encrypt(text, password, {
							keySize: keySize / 32,
						}).toString();
					} else {
						result = CryptoJS.AES.decrypt(text, password, {
							keySize: keySize / 32,
						}).toString(CryptoJS.enc.Utf8);
					}
				} else {
					if (operation === "encrypt") {
						result = CryptoJS.DES.encrypt(text, password, {
							keySize: keySize / 32,
						}).toString();
					} else {
						result = CryptoJS.DES.decrypt(text, password, {
							keySize: keySize / 32,
						}).toString(CryptoJS.enc.Utf8);
					}
				}

				this.resultText = result;
			},
		},
	};
</script>